<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { taskApi } from '@/api'
import { showConfirmDialog, showToast } from 'vant'

const router = useRouter()
const loading = ref(false)
const finished = ref(false)
const refreshing = ref(false)
const tasks = ref([])
const searchValue = ref('')

// 分页参数
const pageParams = ref({
  pageNo: 1,
  pageSize: 10,
  keyword: ''
})

// 加载任务列表
const loadTasks = async (isRefresh = false) => {
  if (isRefresh) {
    pageParams.value.pageNo = 1
    tasks.value = []
    finished.value = false
  }

  loading.value = true

  try {
    const params = {
      ...pageParams.value,
      keyword: searchValue.value
    }

    const result = await taskApi.getTaskList(params)

    if (isRefresh) {
      tasks.value = result.records
    } else {
      tasks.value.push(...result.records)
    }

    // 判断是否还有更多数据
    if (result.records.length < pageParams.value.pageSize) {
      finished.value = true
    } else {
      pageParams.value.pageNo++
    }
  } catch (error) {
    showToast('加载失败: ' + error.message)
  } finally {
    loading.value = false
    refreshing.value = false
  }
}

// 搜索
const onSearch = () => {
  loadTasks(true)
}

// 下拉刷新
const onRefresh = () => {
  refreshing.value = true
  loadTasks(true)
}

// 删除任务
const deleteTask = async (task) => {
  try {
    await showConfirmDialog({
      title: '确认删除',
      message: `确定要删除任务"${task.taskName}"吗？`,
    })

    await taskApi.deleteTask(task.id)
    showToast('删除成功')
    loadTasks(true)
  } catch (error) {
    if (error !== 'cancel') {
      showToast('删除失败: ' + error.message)
    }
  }
}

// 触发下发
const dispatchTask = async (task) => {
  try {
    await showConfirmDialog({
      title: '确认下发',
      message: `确定要触发下发任务"${task.taskName}"吗？`,
    })

    await taskApi.dispatchTask(task.id)
    showToast('下发成功')
    loadTasks(true)
  } catch (error) {
    if (error !== 'cancel') {
      showToast('下发失败: ' + error.message)
    }
  }
}

// 格式化状态
const formatStatus = (status) => {
  const statusMap = {
    'PENDING': '待处理',
    'RUNNING': '运行中',
    'SUCCESS': '成功',
    'FAILED': '失败'
  }
  return statusMap[status] || status
}

// 格式化下发状态
const formatDispatchStatus = (status) => {
  const statusMap = {
    'NOT_STARTED': '未开始',
    'DISPATCHING': '下发中',
    'DISPATCHED': '已下发',
    'FAILED': '失败'
  }
  return statusMap[status] || status
}

// 获取状态颜色
const getStatusColor = (status) => {
  const colorMap = {
    'PENDING': '#ff9500',
    'RUNNING': '#1989fa',
    'SUCCESS': '#07c160',
    'FAILED': '#ee0a24'
  }
  return colorMap[status] || '#969799'
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 下载文件
const downloadFile = async (task) => {
  try {
    const response = await fetch(`http://localhost:18090/api/subscription/files/${task.id}`)
    if (!response.ok) {
      throw new Error('下载失败')
    }

    const blob = await response.blob()
    const url = window.URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = task.fileName || `task_${task.id}_data.csv`
    document.body.appendChild(a)
    a.click()
    window.URL.revokeObjectURL(url)
    document.body.removeChild(a)

    showToast('文件下载成功')
  } catch (error) {
    showToast('下载失败: ' + error.message)
  }
}

onMounted(() => {
  loadTasks(true)
})
</script>

<template>
  <div class="page-container">
    <van-nav-bar
      title="订阅任务管理"
      left-arrow
      @click-left="router.back()"
    />

    <!-- 搜索栏 -->
    <van-search
      v-model="searchValue"
      placeholder="搜索任务名称"
      @search="onSearch"
      @clear="onSearch"
    />

    <!-- 添加按钮 -->
    <van-cell-group>
      <van-cell
        title="新建任务"
        is-link
        @click="router.push('/tasks/create')"
        icon="plus"
      />
    </van-cell-group>

    <!-- 任务列表 -->
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list
        v-model:loading="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="loadTasks"
      >
        <van-cell-group v-for="task in tasks" :key="task.id" class="task-item">
          <van-cell>
            <template #title>
              <div class="task-title">{{ task.taskName }}</div>
            </template>
            <template #label>
              <div class="task-info">
                <div>范围类型: {{ task.scopeType === 'SYSTEM' ? '系统订阅' : '各关订阅' }}</div>
                <div>订阅类型: {{ task.subscribeType === 'DATA' ? '数据' : '月报' }}</div>
                <div>订阅模式: {{ task.subscribeMode === 'RAW' ? '原始数据' : '汇总数据' }}</div>
                <div>数据格式: {{ task.dataFormat }}</div>
                <div>数据源: {{ task.dataSource }}</div>
                <div v-if="task.scopeType === 'SYSTEM' && task.targetSystems">目标系统: {{ task.targetSystems }}</div>
                <div v-if="task.scopeType === 'CUSTOMS' && task.customsCode">关区代码: {{ task.customsCode }}</div>
                <div>结关日期: {{ task.closeDateStart }} 至 {{ task.closeDateEnd }}</div>
                <div>更新时间: {{ formatDateTime(task.updatedTime) }}</div>
              </div>
            </template>
            <template #right-icon>
              <div class="task-actions">
                <van-tag
                  :color="getStatusColor(task.status)"
                  size="small"
                >
                  {{ formatStatus(task.status) }}
                </van-tag>
                <van-tag
                  :color="getStatusColor(task.dispatchStatus)"
                  size="small"
                  style="margin-left: 4px;"
                >
                  {{ formatDispatchStatus(task.dispatchStatus) }}
                </van-tag>
              </div>
            </template>
          </van-cell>

          <van-cell-group>
            <van-cell
              title="编辑"
              is-link
              @click="router.push(`/tasks/${task.id}/edit`)"
              icon="edit"
            />
            <van-cell
              title="触发下发"
              is-link
              @click="dispatchTask(task)"
              icon="send"
              :disabled="task.status === 'RUNNING'"
            />
            <van-cell
              v-if="task.status === 'SUCCESS' && task.fileName"
              title="下载文件"
              is-link
              @click="downloadFile(task)"
              icon="down"
            />
            <van-cell
              title="删除"
              is-link
              @click="deleteTask(task)"
              icon="delete"
              title-style="color: #ee0a24;"
            />
          </van-cell-group>
        </van-cell-group>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<style scoped>
.task-item {
  margin-bottom: 12px;
  border-radius: 8px;
  overflow: hidden;
}

.task-title {
  font-weight: 500;
  font-size: 16px;
  color: #323233;
  line-height: 1.4;
}

.task-info {
  margin-top: 8px;
  font-size: 12px;
  color: #969799;
  line-height: 1.5;
}

.task-info div {
  margin-bottom: 4px;
  padding: 2px 0;
}

.task-actions {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 4px;
}

.van-tag {
  margin-bottom: 2px;
}

.van-cell {
  padding: 12px 16px;
}

.van-cell__title {
  font-size: 16px;
}

.van-cell__label {
  margin-top: 8px;
}
</style>
